import React, {PropsWithChildren, useEffect, useMemo, useState} from 'react'
import {Text, View} from "@tarojs/components";
import styles from "./marketAccount.module.sass"
import marketPageStackStore from "../store/MarketPageStackStore";
import Taro, {useLoad} from "@tarojs/taro";
import {Button, Cell, CellGroup, DatePicker, Tabs} from "@nutui/nutui-react-taro";
import {addMarketAccount, getMarketAccountsByMarketId, MarketAccountResponse} from "../apis/MarketAccountApi";
import {Add} from "@nutui/icons-react-taro";
import {showPrompt} from "../utils/PromptUtils";
import {useMyNavigationBarHeight} from "../components/MyNavigationBar";
import {LocalDate, convert} from "@js-joda/core";
import {
    getMarketSaleDocumentDetailByMonth, MarketSaleDocumentDetail
} from "../apis/MarketSaleDocumentApi";
import Scaffold from "../components/Scaffold";
import ArrayUtils from "@zxy-cn/array-utils";

const MarketAccountSaleDocumentTabPage: React.FC<{ id: number, year: number, month: number, }> = (props) => {
    const [marketSaleDocumentDetail, setMarketSaleDocumentDetail] = useState<MarketSaleDocumentDetail>()

    useEffect(() => {
        getMarketSaleDocumentDetailByMonth(props.id, props.year, props.month).then(response => {
            setMarketSaleDocumentDetail(response.data)
        })
    }, [props.id]);
    return <>
        <CellGroup divider={false}>
            <Cell title={"单品数量"} extra={ArrayUtils.sum(marketSaleDocumentDetail?.items??[],item=>{
                return item.amountInOrder
            })}/>
            <Cell title={"金额小计"} extra={ArrayUtils.sum(marketSaleDocumentDetail?.items??[],item=>{
                return item.totalFee
            })}/>
            {!!marketSaleDocumentDetail?.note && <Cell title={"备注"} extra={marketSaleDocumentDetail.note}/>}
        </CellGroup>

        {marketSaleDocumentDetail?.items.map(item => {
            return <>
                <Cell key={item.id} title={item.name} description={<>
                    <View style={{display: "flex", flexDirection: "column"}}>
                        <Text>条码：{item.barcode}</Text>
                        <Text>零售：{item.price}</Text>
                        <Text>金额：{item.totalFee}</Text>
                    </View>
                </>} onClick={()=>{
                    Taro.navigateTo({
                        url:`/pages/goodsDetail?id=${item.id}`
                    })
                }}/>
            </>
        }) ?? undefined}
    </>
}

export interface MarketAccountProps extends PropsWithChildren {

}

const MarketAccount: React.FC<MarketAccountProps> = ({}) => {

    const marketName = useMemo(() => {
        return marketPageStackStore.detail?.name
    }, [marketPageStackStore.detail?.name])
    const [marketId, setMarketId] = useState<number>()
    useLoad((params) => {
        setMarketId(Number(params.marketId))
    })
    const [data, setData] = useState<MarketAccountResponse[]>([])
    useEffect(() => {
        if (marketId) {
            getMarketAccountsByMarketId(marketId).then(response => {
                setData(response.data)
            })
        }
    }, [marketId]);
    const [showMonthPicker, setShowMonthPicker] = useState(false)
    const [date, setDate] = useState(LocalDate.now().withDayOfMonth(1).minusMonths(1))
    let myNavigationBarHeight = useMyNavigationBarHeight();
    return <>
        <Scaffold title={`${marketName ?? ""}户头`}>
            <View style={{display: 'flex', flexGrow: 1, flexDirection: "column"}}>
                <View className={styles.header}>
                    <Button type={"info"} onClick={() => {
                        setShowMonthPicker(true)
                    }}>{`${date.year()}-${date.monthValue()}`}</Button>
                    <Button type={"primary"} icon={<Add/>} onClick={async () => {
                        let value = await showPrompt({
                            title: "输入户头名称"
                        })
                        let response = await addMarketAccount(marketId!!, {
                            name: value
                        });
                        setData(data.concat({name: value, id: response.data}))
                    }} fill={"outline"}>创建户头</Button>
                </View>
                {!!data?.length && <Tabs autoHeight
                                         style={{flexGrow: 1}}
                                         tabStyle={{position:"sticky",top:myNavigationBarHeight+'px',zIndex:11}}>
                    {data.map(it => {
                        return <Tabs.TabPane key={it.id} title={it.name} >
                            <MarketAccountSaleDocumentTabPage id={it.id} year={date.year()} month={date.monthValue()}/>
                        </Tabs.TabPane>
                    })}
                </Tabs>}
            </View>
        </Scaffold>
        <DatePicker
            title="选择月份"
            type="year-month"
            defaultValue={convert(date).toDate()}
            visible={showMonthPicker}
            onClose={() => setShowMonthPicker(false)}
            onConfirm={(options, _) => {
                setDate(LocalDate.of(Number(options[0]), Number(options[1]), 1))
            }}
        />
    </>
}

export default MarketAccount


